package com.huanglejing.shanggou.utils

import android.Manifest
import android.app.Activity
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.annotation.ColorInt
import android.support.v4.util.ArrayMap
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Space
import android.widget.TextView
import com.afollestad.materialdialogs.GravityEnum
import com.afollestad.materialdialogs.MaterialDialog
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.activity.WatchLargeImageActivity
import com.huanglejing.shanggou.bean.ShareBean
import com.huanglejing.shanggou.common.*
import com.huanglejing.shanggou.data.CacheBitmap
import com.huanglejing.shanggou.rx.RxManager
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.ionicons_typeface_library.Ionicons
import com.tbruyelle.rxpermissions.Permission
import com.tbruyelle.rxpermissions.RxPermissions
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import rx.Subscription
import java.io.Reader
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern

/**
 * Created by Administrator on 2016/10/27 0027.
 */

/*array map*/
fun <K, V> arrayMapOf(): ArrayMap<K, V> = ArrayMap(0)

fun <K, V> arrayMapOf(vararg pairs: Pair<K, V>): ArrayMap<K, V> = ArrayMap<K, V>(pairs.size).apply {
    putAll(pairs)
}

//region number

//region number
//val addressModel by lazy { AddressModelImpl() }

fun String?.toIntOrDefault(def: Int = -1): Int {
    try {
        return this?.toInt() ?: def
    } catch (e: Exception) {
        return def
    }
}


fun String?.convertMoney(): String {
    try {
        if (this == null || TextUtils.isEmpty(this)) {
            return "0.00万元"
        } else {
            val value = java.lang.Float.parseFloat(this)
            if (value >= 10000.0f) {
                val convert = convert(value / 10000.0f)
                return convert + "万元"
            } else {
                return convert(value) + "元"
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
        return "0.00万元"
    }

}

fun convert(money: Any): String {
    val df = java.text.DecimalFormat("#0.00")
    return df.format(money)
}

fun convertLatlnt(num: Double): String {
    val df = java.text.DecimalFormat("#0.000000")
    return df.format(num)
}


fun Any?.tojsonString(): String = AppContext.gson().toJson(this)

fun CharSequence?.toDefault(default: String): String {
    return if (TextUtils.isEmpty(this)) default else this.toString()!!
}


//endregion


//region Subscription
fun Subscription.addTo(rxManager: RxManager) = rxManager.add(this)
//endregion

fun <P : BasePresenter<V>, V : BaseView> AppBaseActivity<P, V>.pinnedToolBar() {
    // ToastUtils.toastLong("statusBarHeight${ DisplayUtils.`$statusBarHeight`(viewContext)}\r\n  toolbarHeight${DisplayUtils.`$toolbarHeight`(viewContext)}")
    KLog.e("statusBarHeight${DisplayUtils.`$statusBarHeight`(viewContext)}\r\n  toolbarHeight${DisplayUtils.`$toolbarHeight`(viewContext)}")
    this.toolbarLayout?.addView(Space(this).apply {
        // layoutParams = ViewGroup.MarginLayoutParams(0, DisplayUtils.`$statusBarHeight`(viewContext) + DisplayUtils.`$toolbarHeight`(viewContext))
        layoutParams = ViewGroup.MarginLayoutParams(0, DisplayUtils.`$toolbarHeight`(viewContext))
    }, 0)
}


inline fun <reified T> Gson.fromJson(json: String?) = this.fromJson<T>(json, object : TypeToken<T>() {}.type)
inline fun <reified T> Gson.fromJson(json: JsonElement?) = this.fromJson<T>(json, object : TypeToken<T>() {}.type)
inline fun <reified T> Gson.fromJson(json: Reader?) = this.fromJson<T>(json, object : TypeToken<T>() {}.type)
inline fun <reified T> Gson.fromJson(json: JsonReader?) = this.fromJson<T>(json, object : TypeToken<T>() {}.type)

//fun List<Address>.findCityByCityId(cityCode: String): CityEvent? {
//    val filter = cityCode.substring(0, 2)
//    this.forEachIndexed { index, address ->
//        if ((address.code?.startsWith(filter) ?: false)) { //北京|上海特殊处理
//            for (cityBean in address.cityArr) {
//                if (cityBean.code == cityCode) {
//                    return CityEvent(address.name!!, cityBean.name!!, cityBean.code!!)
//                }
//            }
//        }
//
//    }
//    return null
//}
//
//fun List<Address>.findCityByAreaId(areaCode: String): CityEvent? {
//    val first = areaCode.substring(0, 2)
//    val second = areaCode.substring(0, 4)
//    this.forEachIndexed { index, address ->
//        if (address.code?.startsWith(first) ?: false) {
//            for (cityBean in address.cityArr) {
//                if (cityBean.code?.startsWith(second) ?: false) {
//                    for (areaBean in cityBean.areaArr) {
//                        if (areaBean.code == areaCode) {
//                            return CityEvent(address.name!!, cityBean.name!!, areaBean.name!!, address.code!!, cityBean.code!!,
//                                    areaBean.code!!, "", "")
//                        }
//                    }
//                }
//            }
//        }
//    }
//    return null
//}


fun Any?.checkEmpty(): Boolean {
    if (null == this) return true
    return when (this) {
        is CharSequence -> this.isBlank()
        is Collection<*> -> this.isEmpty()
        is Map<*, *> -> this.isEmpty()
        is Sequence<*> -> this.toList().isEmpty()
        is TextView -> TextUtils.isEmpty(this.text)
        //todo
        else -> false
    }
}

/*context*/

/*Context*/
val Context.inflater: LayoutInflater
    inline get() = LayoutInflater.from(this)

private fun inflateView(context: Context, layoutResId: Int, parent: ViewGroup?,
                        attachToRoot: Boolean): View =
        LayoutInflater.from(context).inflate(layoutResId, parent, attachToRoot)

fun Context.inflate(layoutResId: Int, parent: ViewGroup? = null, attachToRoot: Boolean = false): View =
        inflateView(this, layoutResId, parent, attachToRoot)


inline fun Context.autoBindService(clazz: Class<out Service>, params: Bundle = Bundle(), servieConn: () -> ServiceConnection) {
    val serIntent = Intent(this, clazz)
    serIntent.putExtras(params)
    this.startService(serIntent)
    this.bindService(serIntent, servieConn(), android.content.Context.BIND_AUTO_CREATE)
}


fun Activity.showDialog(title: String, arr: List<String>, select: Int = -1, fu: (which: Int, text: CharSequence) -> Unit = { i, t -> }) {
    MaterialDialog.Builder(this).title(title).items(arr)
            .itemsCallbackSingleChoice(select) { dialog, itemView, which, text ->
                fu(which, text ?: "")
                true
            }.onPositive { materialDialog, dialogAction -> fu(materialDialog.selectedIndex, arr[materialDialog.selectedIndex]) }.show()
}

fun Iterable<String>.lookForIndex(t: String): Int = this.indexOfFirst { it == t.trim() }


fun Context.callPhones(phones: List<String>, phoneStateListener: PhoneStateListener? = null) {
    fun startCall(phone: String) {
        if (phone.isTelephoneMobileNum()) {
            if (phoneStateListener != null) {
                val telMannger = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                telMannger.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
            }
            val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone))
            startActivity(intent)
        } else {
            ToastUtils.toastLong("不是有效的手机号码")
        }

    }

    RxPermissions.getInstance(this).request(Manifest.permission.CALL_PHONE)
            .subscribe(object : SimpleSubscriber<Boolean>() {
                override fun onNext(permission: Boolean) {
                    super.onNext(permission)
                    if (permission!!) {
                        if (phones.size == 1) {
                            MaterialDialog.Builder(this@callPhones)
                                    .titleGravity(GravityEnum.CENTER)
                                    .contentGravity(GravityEnum.CENTER)
                                    .buttonsGravity(GravityEnum.CENTER)
                                    .itemsGravity(GravityEnum.CENTER)
                                    .backgroundColor(Color.WHITE)
                                    .title("是否拨打")
                                    .titleColor(Color.BLACK)
                                    .content(phones.first())
                                    .contentColor(Color.BLACK)
                                    .negativeText("否")
                                    .negativeColor(AppContext.get().resources.getColor(R.color.level_error))
                                    .positiveText("是")
                                    .positiveColor(AppContext.get().resources.getColor(R.color.level_confirm))
                                    .onPositive { dialog, which ->
                                        dialog.dismiss()
                                        startCall(phones.first())
                                    }.show()
                        } else if (phones.size > 1) {
                            MaterialDialog.Builder(this@callPhones)
                                    .title("请选择号码")
                                    .items(phones)
                                    .positiveText("确定")
                                    .negativeText("取消")
                                    .titleGravity(GravityEnum.CENTER)
                                    .contentGravity(GravityEnum.CENTER).buttonsGravity(GravityEnum.CENTER)
                                    .itemsCallbackSingleChoice(0) { dialog, itemView, which, text -> true }
                                    .onPositive { materialDialog, dialogAction ->
                                        startCall(phones[materialDialog.selectedIndex])
                                        materialDialog.dismiss()
                                    }.show()
                        } else {
                            ToastUtils.toastLong("对不起,对方没有有效的电话号码")
                        }

                    } else {
                        val build = MaterialDialog.Builder(this@callPhones)
                                .cancelable(false)
                                .positiveText("同意")
                                .negativeText("不同意").build()
                        build.builder.cancelable(false).content(String.format("没有权限", AppContext.get().resources.getString(R.string.app_name), "打电话"))
                                .positiveText("去设置").negativeText("").onPositive(MaterialDialog.SingleButtonCallback { dialog, which ->
                                    val packageURI = Uri.parse("package:" + AppContext.get().packageName)
                                    KLog.d(packageURI)
                                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                                    startActivity(intent)
                                }).show()
                    }
                }
            })


}


//view  measure

fun View.measureIfNotMeasure() {
    if (this.measuredHeight != 0 || this.measuredWidth != 0) return
    this.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
}

fun Context.close() {
    (this as? Activity)?.finish()
}


fun Activity.watchLargeImage(arrayList: List<String>, pos: Int = 0) {
    if (arrayList.checkEmpty() || arrayList.size < 1) {
        ToastUtils.toastLong("暂无有效的头像地址")
    } else {
        WatchLargeImageActivity.startShow(this, arrayList, pos)
    }

}

fun Activity.toQQ(qq: String) {
    val url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq
    this.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
//指定的QQ号只需要修改uin后的值即可。
}


/*IIcon*/
fun Int.toColorInt() = UIUtils.getColor(this)

fun createIcon(icon: Ionicons.Icon, sizeDp: Int = 24, paddingdp: Int = 4, @ColorInt color: Int = R.color.white.toColorInt()) = IconicsDrawable(AppContext.get(), icon).sizeDp(sizeDp).paddingDp(paddingdp).color(color)!!
fun createIcon(icon: String, sizeDp: Int = 24, paddingdp: Int = 4, @ColorInt color: Int = R.color.white.toColorInt()) = IconicsDrawable(AppContext.get(), icon).sizeDp(sizeDp).paddingDp(paddingdp).color(color)!!


inline fun Activity.bindService(clazz: Class<out Service>, servieConn: () -> ServiceConnection) {
    val serIntent = Intent(this, clazz)
    this.startService(serIntent)
    this.bindService(serIntent, servieConn(), android.content.Context.BIND_AUTO_CREATE)
}

fun BaseActivity.showDialog(title: String, arr: List<String>, select: Int = -1, fu: (which: Int, text: CharSequence) -> Unit = { i, t -> }) {
    MaterialDialog.Builder(this).title(title).items(arr)
            .itemsCallbackSingleChoice(select) { dialog, itemView, which, text ->
                fu(which, text ?: "")
                true
            }.onPositive { materialDialog, dialogAction -> fu(materialDialog.selectedIndex, arr[materialDialog.selectedIndex]) }.show()
}


//验证是否为数字ֻ(包含小数点)
fun String.toNumberStr(): String? {
    return try {
        BigDecimal(this).toString()
    } catch (ex: NumberFormatException) {
        if (this == "价格面议") "0"
        else null
    }

}

//验证数字是否最多为两位小数
fun isTwoAfterPoint(num: String?): Boolean {
    return num?.toNumberStr()?.let {
        (it.split(".").getOrNull(1)?.length ?: 0) <= 2
    } ?: false
}

//验证数字小数点之前最多9位
fun isNineBeforePoint(num: String?): Boolean {
    return num?.toNumberStr()?.let {
        (it.split(".").firstOrNull()?.length ?: 10) <= 9
    } ?: false
}


//验证是否是微信或者QQ
fun isQQOrWX(qqorwx: String): Boolean {
    if (TextUtils.isEmpty(qqorwx)) {
        return false;
    }
//QQ号最短5位，微信号最短是6位最长20位
    val p = Pattern.compile("^[a-zA-Z0-9_-]{5,19}$");
    val m = p.matcher(qqorwx);
    return m.matches();
}

// 判断格式是否为email
fun isEmail(email: String): Boolean {
    if (TextUtils.isEmpty(email)) {
        return false;
    }
    val p = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")
    val m = p.matcher(email)
    return m.matches()
}

//TODO  此处只能判断手机号码  不可以判断电话号码  调用的时候要注意
// TODO  手机号码验证准则改变时还需改正 AddFriendActivity 132-133行
fun String.isTelephoneMobileNum(): Boolean {
    return !this.checkEmpty() && ((this.equals("4008989897")
            || this.equals("400-8989-897")) ||
            this.matches("^(0\\d{2,3}-\\d{7,8}(-\\d{3,5})?)|(13[0-9]|14[57]|15[0-35-9]|17[0-9]|18[0-9])[0-9]{8}$".toRegex()))
}


fun getCurrentDate(): List<Int> {
    try {
        val date = Date(System.currentTimeMillis())
        val sdf = SimpleDateFormat("yyyy-MM-dd-hh-mm-ss")
        val timeList = sdf?.format(date ?: Date())?.split("-")
        return timeList?.map { it.toIntOrNull() ?: 0 } ?: emptyList()
    } catch (e: Exception) {
        return emptyList()
    }
}

fun getCurrentYear(): Int {
    return getCurrentDate().getOrNull(0) ?: 2017
}

fun getCurrentMonth(): Int {
    return getCurrentDate().getOrNull(1) ?: 4
}

fun getCurrentDay(): Int {
    return getCurrentDate().getOrNull(2) ?: 20
}

fun getNowTime(): Long {
    return System.currentTimeMillis()
}

/***
 * 获取控件的宽高值  适用于在控件未展示  未加载的时候
 * @param view
 * @return
 */
fun unDisplayViewSize(view: View?): IntArray {
    val size = IntArray(2)
    if (view == null) {
        size[0] = 0
        size[1] = 0
        return size;
    }
    val width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    val height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    view?.measure(width, height)
    size[0] = view?.measuredWidth ?: 0
    size[1] = view?.measuredHeight ?: 0
    return size
}

fun Context.oneKeyShare(bean: ShareBean) {
    //UmengTool.getSignature(this)
    /**
     * 调用第三方一键分享
     */
    //安卓6.0  动态添加权限(一键分享调用)
    RxPermissions.getInstance(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION)
            .filter { !it.granted }
            .firstOrDefault(null)
            .subscribe(object : SimpleSubscriber<Permission?>() {
                override fun onNext(permission: Permission?) {
                    super.onNext(permission)
                    if (permission == null && !bean.checkEmpty()) {
                        //        UmengTool.getSignature(activity)
                        try {
                            ShareAction(AppManager.currentActivity() ?: AppContext.nowActivity)
                                    .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.SINA, SHARE_MEDIA.QQ,
                                            SHARE_MEDIA.QZONE)
                                    .setShareboardclickCallback { v, sharE_MEDIA ->
                                        UMHelper.getInstance().startShare(AppManager.currentActivity()
                                                ?: AppContext.nowActivity, sharE_MEDIA, bean)
                                    }
                                    .open()
                        } catch (e: Exception) {
                            KLog.e("share error $e")
                        }
                    } else {
                        if (permission?.name == Manifest.permission.ACCESS_FINE_LOCATION) {
                            ToastUtils.toastLong(String.format(getString(R.string.no_permission), getString(R.string.app_name), "定位"))
                        } else {
                            ToastUtils.toastLong(String.format(getString(R.string.no_permission), getString(R.string.app_name), "存储"))
                        }
                        KLog.e("没有权限${permission?.name}")
                    }
                }
            })
}

fun Context.oneKeyShare(bean: ShareBean, media: SHARE_MEDIA) {
    //UmengTool.getSignature(this)
    /**
     * 调用第三方一键分享
     */
    //安卓6.0  动态添加权限(一键分享调用)
    RxPermissions.getInstance(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION)
            .filter { !it.granted }
            .firstOrDefault(null)
            .subscribe(object : SimpleSubscriber<Permission?>() {
                override fun onNext(permission: Permission?) {
                    super.onNext(permission)
                    if (permission == null && !bean.checkEmpty()) {
                        //        UmengTool.getSignature(activity)
                        try {
                            bean.text = resources.getString(R.string.str_share_content)
                            bean.targetUrl = "http://dadisoft.cn/sg/index.html"
                            bean.title = resources.getString(R.string.app_name)
                            bean.setImage(CacheBitmap)
                            UMHelper.getInstance().startShare(AppManager.currentActivity()
                                    ?: AppContext.nowActivity, media, bean)
                        } catch (e: Exception) {
                            KLog.e("share error $e")
                        }
                    } else {
                        if (permission?.name == Manifest.permission.ACCESS_FINE_LOCATION) {
                            ToastUtils.toastLong(String.format(getString(R.string.no_permission), getString(R.string.app_name), "定位"))
                        } else {
                            ToastUtils.toastLong(String.format(getString(R.string.no_permission), getString(R.string.app_name), "存储"))
                        }
                        KLog.e("没有权限${permission?.name}")
                    }
                }
            })
}

fun formatNum(value: Any?): String {
    if (value.checkEmpty()) {
        return "0"
    }
    try {
        var replace = "0"
        if (value is String) {
            var toDoubleOrNull = value?.toDoubleOrNull() ?: 0
            replace = String.format("%.3f", toDoubleOrNull) ?: "0"
        } else {
            replace = String.format("%.3f", value) ?: "0"
        }
     //   var replace = "0"
       /* if (result.endsWith(".000")) {
            replace = result.replace(".000", "")
        } else {
            replace = result
        }*/
        if (replace.contains(".")){
            var split = replace.split(".")
            for (i in split[1].length downTo 0) {
                if (replace.endsWith("0")){
                    replace=replace.substring(0,replace.length-1)
                }
            }
        }
       if (replace.endsWith(".")){
           replace=replace.substring(0,replace.length-1)
       }
        return replace
    } catch (e: Exception) {
    }
    return "0"
}

fun cacheLoginInfo(userName: String, customerId: String) {
    //xml文件存入账号信息
    val share = AppContext.get().getSharedPreferences(C.Preference.SAHNGOU_DATA, Context.MODE_PRIVATE)
    val edit = share.edit()
    if (!userName.checkEmpty()) {
        edit.putString(C.Preference.CACHE_ACCOUNT_NAME, userName ?: "")
    } else {
        edit.putString(C.Preference.CACHE_ACCOUNT_NAME, "")
    }
    if (!customerId.checkEmpty()) {
        edit.putString(C.Preference.CACHE_ACCOUNT_ID, customerId ?: "")
    } else {
        edit.putString(C.Preference.CACHE_ACCOUNT_ID, "")
    }
    edit.apply()
}

fun cacheLoginParams(nameNoZero: String, name: String, pwd: String) {
    //xml文件存入账号信息
    val share = AppContext.get().getSharedPreferences(C.Preference.SAHNGOU_DATA, Context.MODE_PRIVATE)
    val edit = share.edit()
    if (!name.checkEmpty()) {
        edit.putString(C.Preference.CACHE_ACCOUNT_NAME, name ?: "")
        edit.putString(C.Preference.CACHE_ACCOUNT_NAME_NOZERO, nameNoZero ?: "")
    } else {
        edit.putString(C.Preference.CACHE_ACCOUNT_NAME, "")
        edit.putString(C.Preference.CACHE_ACCOUNT_NAME_NOZERO, "")
    }
    if (!pwd.checkEmpty()) {
        edit.putString(C.Preference.CACHE_ACCOUNT_PWD, pwd ?: "")
    } else {
        edit.putString(C.Preference.CACHE_ACCOUNT_PWD, "")
    }
    edit.apply()
}

fun drawableToBitmap(drawable: Drawable?): Bitmap? { // drawable 转换成bitmap
    if (drawable == null) {
        return null
    }
    val width = drawable.getIntrinsicWidth();// 取drawable的长宽
    val height = drawable.getIntrinsicHeight();
    var config: Bitmap.Config? = null
    if (drawable.getOpacity() != PixelFormat.OPAQUE) {  // 取drawable的颜色格式
        config = Bitmap.Config.ARGB_8888
    } else {
        config = Bitmap.Config.RGB_565
    }
    val bitmap = Bitmap.createBitmap(width, height, config);// 建立对应bitmap
    val canvas = Canvas(bitmap);// 建立对应bitmap的画布
    drawable.setBounds(0, 0, width, height);
    drawable.draw(canvas);// 把drawable内容画到画布中
    return bitmap;
}